package com.supermarket.manage.business.usermanage.controller;

import com.supermarket.manage.common.constant.RoleConstant;
import com.supermarket.manage.common.dto.CodeStatus;
import com.supermarket.manage.common.dto.ResponseResult;
import com.supermarket.manage.common.dto.ucenter.request.AddRoleParams;
import com.supermarket.manage.common.dto.ucenter.request.RoleAddPermissionParams;
import com.supermarket.manage.common.dto.ucenter.request.RoleUpdateParams;
import com.supermarket.manage.common.pojo.Role;
import com.supermarket.manage.provider.api.ucenter.RoleManageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @author Faxon
 * @version 1.0
 * @date 2020-02-29 18:42
 **/
@RestController
@RequestMapping("/roleManage")
@Api(value = "RoleManageController", tags = "角色管理接口")
public class RoleManageController {

    @Reference(version = "1.0.0")
    private RoleManageService roleManageService;

    @PreAuthorize("hasAnyAuthority('/','/user/get')")
    @GetMapping("/getRoleList/{buyerId}")
    @ApiOperation(value = "获取所有角色列表", notes = "获取所有角色列表")
    public ResponseResult<List<Role>> getRoleListByBuyerId(@NotBlank(message = "客户id不能为空")
                                                           @PathVariable("buyerId") String buyerId) {
        List<Role> roleList = roleManageService.getRoleListByBuyerId(buyerId);
        if (roleList == null || roleList.size() == 0) {
            return new ResponseResult<>(CodeStatus.FAIL, "查询失败");
        }
        return new ResponseResult<>(CodeStatus.OK, "查询成功", roleList);
    }

    @PreAuthorize("hasAnyAuthority('/','/user/get')")
    @GetMapping("/getRoleById/{roleId}")
    @ApiOperation(value = "根据id获取角色信息", notes = "根据id获取角色信息")
    public ResponseResult<Role> getRoleById(@NotNull(message = "roleId不能为空")
                                            @PathVariable("roleId") Long roleId) {
        Role role = roleManageService.getRoleById(roleId);
        if (role != null) {
            return new ResponseResult<>(CodeStatus.OK, "查询成功", role);
        }
        return new ResponseResult<>(CodeStatus.FAIL, "未查询到此角色信息");
    }

    @PreAuthorize("hasAnyAuthority('/','/user/manage')")
    @PostMapping("/addRole")
    @ApiOperation(value = "添加角色", notes = "必传参数：buyerId，name，enname，permissionIds")
    public ResponseResult<Void> addRole(@Validated @RequestBody AddRoleParams params) {
        if (RoleConstant.isConflictWithBaseRoleName(params.getName())) {
            return new ResponseResult<>(CodeStatus.ILLEGAL_REQUEST, "角色名称与基础角色名称冲突");
        }
        if (roleManageService.getRoleCountByBuyerId(params.getBuyerId()) > RoleConstant.MAX_ROLE_COUNT) {
            return new ResponseResult<>(CodeStatus.FAIL, "添加失败：每个用户最多可自定义5个角色数");
        }
        Boolean aBoolean = roleManageService.addRole(params);
        if (aBoolean) {
            return new ResponseResult<>(CodeStatus.OK, "添加成功");
        }
        return new ResponseResult<>(CodeStatus.FAIL, "添加失败");
    }


    @PreAuthorize("hasAnyAuthority('/','/user/manage')")
    @PostMapping("/updateRoleById")
    @ApiOperation(value = "修改角色基本信息", notes = "必传参数：id，name，enname")
    public ResponseResult<Void> updateRoleById(@Validated @RequestBody RoleUpdateParams params) {
        if (RoleConstant.isBaseRoleId(params.getId())) {
            return new ResponseResult<>(CodeStatus.ILLEGAL_REQUEST, "基础角色不可修改");
        }
        if (RoleConstant.isConflictWithBaseRoleName(params.getName())) {
            return new ResponseResult<>(CodeStatus.ILLEGAL_REQUEST, "角色名称与基础角色名称冲突");
        }
        Boolean aBoolean = roleManageService.updateRoleById(params);
        if (aBoolean) {
            return new ResponseResult<>(CodeStatus.OK, "修改成功");
        }
        return new ResponseResult<>(CodeStatus.FAIL, "修改失败");
    }

    @PreAuthorize("hasAnyAuthority('/','/user/manage')")
    @GetMapping("/deleteRoleById/{roleId}")
    @ApiOperation(value = "删除角色", notes = "删除角色")
    public ResponseResult<Void> deleteRoleById(@NotNull(message = "角色id不能为空")
                                               @PathVariable("roleId") Long roleId) {
        if (RoleConstant.isBaseRoleId(roleId)) {
            return new ResponseResult<>(CodeStatus.ILLEGAL_REQUEST, "基础角色不可删除");
        }
        Integer count = roleManageService.getUsingCountByRoleId(roleId);
        if (count > 0) {
            return new ResponseResult<>(CodeStatus.FAIL, "删除失败，该角色已被赋予用户");
        }
        Boolean aBoolean = roleManageService.deleteRoleById(roleId);
        if (aBoolean) {
            return new ResponseResult<>(CodeStatus.OK, "删除成功");
        }
        return new ResponseResult<>(CodeStatus.FAIL, "删除失败");
    }

    @PreAuthorize("hasAnyAuthority('/','/user/manage')")
    @PostMapping("/addPermissionToRole")
    @ApiOperation(value = "为角色添加（修改）权限", notes = "为角色添加（修改）权限")
    public ResponseResult<Void> addPermissionToRole(@Validated @RequestBody RoleAddPermissionParams roleAddPermissionParams) {
        if (RoleConstant.isBaseRoleId(roleAddPermissionParams.getRoleId())) {
            return new ResponseResult<>(CodeStatus.ILLEGAL_REQUEST, "基础角色不可更改权限");
        }
        Boolean aBoolean = roleManageService.addPermissionToRole(roleAddPermissionParams);
        if (aBoolean) {
            return new ResponseResult<>(CodeStatus.OK, "操作成功");
        }
        return new ResponseResult<>(CodeStatus.FAIL, "操作失败");
    }
}
